#include <iostream>
#include <string>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

static void Usage(const std::string& proc)
{
    std::cout << "Usage\n" << proc << " serverip serverport\n" << std::endl;
}

int main(int argc, char** argv)
{
    if(argc != 3)
    {
        Usage(argv[0]);
        return 3;
    }
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(sockfd < 0)
    {
        std::cout << "create sockfd failed" << std::endl;
        return 1;
    }

    struct sockaddr_in server;
    socklen_t len = sizeof(server);
    bzero(&server, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(std::stoi(argv[2]));
    server.sin_addr.s_addr = inet_addr(argv[1]);

    // if(bind(sockfd, (struct sockaddr*)&server, sizeof(server)) < 0)
    // {
    //     std::cout << "bind socket failed" << std::endl;
    //     perror("bind");
    //     return 2;
    // }

    // 开始通信
    std::string message;
    char buffer[64];
    while(true)
    {
        std::cout << "Please Enter# ";
        std::getline(std::cin, message);
        sendto(sockfd, message.c_str(), message.size(), 0, (struct sockaddr*)&server, sizeof(server));
        int n = recvfrom(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr*)&server, &len);
        if(n > 0)
        {
            buffer[n] = 0;
            std::cout << buffer << std::endl;
        }
    }
    return 0;
}